import {
  postForm
}
from '../../../utils/request'
Page({

  data: {
    selectedSku: {},
    TRADE_TIPS: '', // 温馨提示
    REFUND_TERMS: '', // 退改说明
    showSkuSelectDialog: false,
    mobile: '获取手机号码',
    agreeProtocol: false,
    showAgreeDialog: false,
    showLoginDialog: false,
  },

  onLoad(options) {
    let id = options.spuId;
    if (!id) {
      wx.switchTab({
        url: '/pages/goods/goods',
      })
      return;
    }
    let mobile = wx.getStorageSync('mobile') || '获取手机号码';
    this.setData({
      id: id,
      mobile: mobile
    })
    this.getSpu();
    this.getTerms();
  },
  onReady() {},
  onShow() {},
  onHide() {},
  onUnload() {},
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {},
  getPhoneNumber(e) {
    if (!e.detail.code) {
      wx.showToast({
        title: '无法获取手机号',
        icon: 'none'
      })
      return;
    }
    let code = e.detail.code;
    postForm({
      url: 'front/api/user/mobile',
      data: {
        code: code
      }
    }).then(resp => {
      let mobile = resp;
      this.setData({
        mobile: mobile
      });
      wx.setStorageSync('mobile', mobile);
    })
  },
  getSpu() {
    postForm({
      url: `front/api/goods/spu/${this.data.id}`
    }).then(resp => {
      this.setData({
        target: resp,
        selectedSku: resp.skuList[0]
      })
    })
  },
  clickSkuSelect() {
    if (this.data.target.skuList.length == 1) {
      return;
    }
    this.setData({
      showSkuSelectDialog: true,
      tempSelectedSku: this.data.selectedSku
    })
  },
  selectSku(e) {
    let id = e.currentTarget.dataset.id;
    let sku = {};
    this.data.target.skuList.forEach(item => {
      if (item.id == id) {
        sku = item;
      }
    });
    this.setData({
      tempSelectedSku: sku,
    })
  },
  confirmSelectSku() {
    this.setData({
      selectedSku: this.data.tempSelectedSku,
      showSkuSelectDialog: false
    })
  },
  closeDialog(e) {
    if (e.target.dataset.role == 'mask') {
      this.setData({
        showSkuSelectDialog: false
      })
    }
  },
  getTerms() {
    let names = ['TRADE_TIPS', 'REFUND_TERMS'];
    postForm({
      url: 'front/api/system/config/get',
      data: {
        names: names.join(',')
      }
    }).then(resp => {
      this.setData({
        TRADE_TIPS: resp['TRADE_TIPS'],
        REFUND_TERMS: resp['REFUND_TERMS']
      })
    })
  },
  // 点击支付
  clickPay() {
    if (!this.data.agreeProtocol) {
      this.setData({
        showAgreeDialog: true
      })
      return false;
    }
    let mobile = this.data.mobile.replace(/\D/gi, '');
    if (!mobile) {
      this.setData({
        showLoginDialog: true
      })
      return false;
    }
    postForm({
      url: `front/api/trade/buy/${this.data.selectedSku.id}`
    }).then(resp => {
      let trade = resp.trade;
      let param = resp.response;
      wx.requestPayment({
        timeStamp: param.timeStamp,
        nonceStr: param.nonceStr,
        package: param.packageVal,
        signType: param.signType,
        paySign: param.paySign,
        success(resp) {
          console.info(resp)
          if (resp.errMsg == 'requestPayment:ok') {
            // 支付成功
            wx.navigateTo({
              url: '/pages/goods/buyResult/result?id=' + trade.id,
            })
          }
        },
        fail(resp) {
          console.info('error...')
          console.info(resp)
          wx.showToast({
            title: '支付失败',
            icon: 'error',
          })
        }
      })
    }).catch(() => {

      // wx.navigateTo({
      //   url: '/pages/goods/buyResult/result?id=' + 78,
      // })
    })
  },
  clickAgree(e) {
    this.setData({
      agreeProtocol: !this.data.agreeProtocol
    })
  },
  handleOpenPrivacyContract() {
    wx.openPrivacyContract({
      success: () => {}, // 打开成功
      fail: () => {}, // 打开失败
      complete: () => {}
    })
  },
})